﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using LEEAAttendanceControl.Web;
using LEEAAttendanceControl.Web.Services;
using System.ServiceModel.DomainServices.Client;

namespace LEEAAttendanceControl.Views
{
    public partial class PunchEdit : ChildWindow
    {
        LEEAContext context = new LEEAContext();

        int hourID = 0;
        int employeeID = 0;

        Hour hour = new Hour();

        public PunchEdit()
        {
            InitializeComponent();
        }

        public PunchEdit(string title)
        {
            Title = title;

            InitializeComponent();
        }

        public void LoadData(int id, int empID)
        {
            hourID = id;
            employeeID = empID;

            context.Load(context.GetShiftsByCompanyIDQuery(((App) Application.Current).CompanyID.Value)
                , OnShiftLoadCompleted, null);
        }

        public void OnShiftLoadCompleted(LoadOperation load)
        {
            ShiftCombo.ItemsSource = load.Entities;

            context.Load(context.GetHourByIdQuery(hourID), OnHoursLoadCompleted, null);
        }

        public void OnHoursLoadCompleted(LoadOperation load)
        {
            hour = (Hour)load.Entities.FirstOrDefault();

            if (hour == null)
            {
                hour = new Hour();

                hour.EmployeeID = employeeID;

                context.Hours.Add(hour);
            }

            DataContext = hour;
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            context.SubmitChanges(OnChangedSubmitted, null);
        }

        protected void OnChangedSubmitted(SubmitOperation so)
        {
            if (so.HasError)
            {
                so.MarkErrorAsHandled();
            }
            else
            {
                MessageBox.Show(ApplicationStrings.GeneralSave, ApplicationStrings.GeneralSave, MessageBoxButton.OK);

                App myApp = (App)Application.Current;

                myApp.InvokeChangeEmployeesEvent(null, new EventArgs());

                this.Close();
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }
    }
}